package com.pig4cloud.pig.module.controller.promoter;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.promoter.Promoter;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.promoter.IPromoterService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 平台推广员Controller
 *
 * @author ruoyi
 * @date 2022-06-15
 */
@Validated
@Api(value = "平台推广员控制器", tags = {"平台推广员管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/promoter")
public class PromoterController {

    private final IPromoterService promoterService;
	private final IWxUserService wxUserService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

	@Value("${ruoyi.profile}")
	private String uploadPath;
    /**
     * 查询平台推广员列表
     */
    @ApiOperation("查询平台推广员列表")
    @PreAuthorize("@pms.hasPermission('module:promoter:list')")
    @GetMapping("/list")
    public TableDataInfo<Promoter> list(@Validated Promoter promoter) {
        QueryWrapper<Promoter> qw = new QueryWrapper<>();
        qw.eq("check_state",1);
		if(StrUtil.isNotEmpty(promoter.getName())){
			qw.like("phone_num",promoter.getName()).or().like("name",promoter.getName());
		}
        if(promoter.getGroupId()!=null){
            qw.eq("group_id",promoter.getGroupId());
        }
        qw.orderByDesc("id");

        TableDataInfo<Promoter> td = PageUtils.buildDataInfo(promoterService.page(PageUtils.buildPage(),qw));
        List<Promoter> list = td.getData();
        list.forEach(promoter1 -> {
            if(StrUtil.isNotEmpty(promoter1.getQrCode())){
                promoter1.setQrCode(imgUrl + promoter1.getQrCode());
            }

            if(promoter1.getWxUserId()!=null){
				WxUser wxUser = wxUserService.findById(promoter1.getWxUserId());
				if(wxUser != null){
					promoter1.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						promoter1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
				}
			}

            QueryWrapper<WxUser> qwUser = new QueryWrapper<>();
			qwUser.eq("promoter_id",promoter1.getId());
			if(StrUtil.isNotEmpty(promoter.getBeginDate())){
                qwUser.between("create_time",promoter.getBeginDate() + " 00:00:00",promoter.getEndDate() + " 23:59:59");
            }
            long userCount = wxUserService.count(qwUser);
			promoter1.setInviteUserCount(userCount);
        });
        return td;
    }
    @ApiOperation("查询平台推广员列表")
    @PreAuthorize("@pms.hasPermission('module:promoter:list')")
    @GetMapping("/checkList")
    public TableDataInfo<Promoter> checkList(@Validated Promoter promoter) {
        QueryWrapper<Promoter> qw = new QueryWrapper<>();
        if (promoter.getCheckState()!=null){
            qw.eq("check_state",promoter.getCheckState());
        }
		if(StrUtil.isNotEmpty(promoter.getName())){
			qw.like("phone_num",promoter.getName()).or().like("name",promoter.getName());
		}
        TableDataInfo<Promoter> td = PageUtils.buildDataInfo(promoterService.page(PageUtils.buildPage(),qw));
        List<Promoter> list = td.getData();
        list.forEach(promoter1 -> {
            if(promoter1.getWxUserId()!=null){
                WxUser wxUser = wxUserService.findById(promoter1.getWxUserId());
                if(wxUser!=null){
					promoter1.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						promoter1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
                }
            }
        });
        return td;
    }

    /**
     * 导出平台推广员列表
     */
    @ApiOperation("导出平台推广员列表")
    @PreAuthorize("@pms.hasPermission('module:promoter:export')")
    @SysLog("平台推广员")
    @GetMapping("/export")
    public List export(@Validated Promoter promoter) {
        QueryWrapper<Promoter> qw=new QueryWrapper<>();
        if (promoter.getGroupId()!=null){
            qw.eq("group_id",promoter.getGroupId());
        }
        List<Promoter> list = promoterService.list(qw);
        for(Promoter list1:list){
            if(list1.getWxUserId()!=null){
                WxUser wxUser = wxUserService.findById(list1.getWxUserId());
                if(wxUser!=null){
                    list1.setUserName(wxUser.getNickName());
                }
            }
        }
        // ExcelUtil<Promoter> util = new // ExcelUtil<Promoter>(Promoter.class);
        return  list;// util.exportExcel(list, "平台推广员");
    }

    /**
     * 获取平台推广员详细信息
     */
    @ApiOperation("获取平台推广员详细信息")
    @PreAuthorize("@pms.hasPermission('module:promoter:query')")
    @GetMapping("/{id}")
    public R<Promoter> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Promoter promoter = promoterService.getById(id);
        if(promoter!=null){
        	List<WxUser> wxUsers = new ArrayList<>();
        	if(promoter.getIsHasCash() == 1){
        		if(promoter.getWxUserId()!=null){
        			WxUser wxUser = wxUserService.findById(promoter.getWxUserId());
        			if(wxUser!=null){
						wxUsers.add(wxUser);
					}
				}
			}
        	promoter.setWxUsers(wxUsers);
		}
        return R.ok(promoter);
    }

    /**
     * 新增平台推广员
     */
    @ApiOperation("新增平台推广员")
    @PreAuthorize("@pms.hasPermission('module:promoter:add')")
    @SysLog("平台推广员")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody Promoter promoter) {
        promoter.setCreateTime(new Date());
		String img_key = "";
		boolean bl = promoterService.save(promoter);
        if(bl){
            try{
                String userNo = "P"+ new Date().getTime();
                promoter.setUserNo(userNo);
                String qrCode = "";
                String fileName = "promoter_qr_" + promoter.getUserNo() + ".jpg";
                String content = "https://www.sdyuedou.com/wxmini/promoter/getInfo?pid=" + promoter.getId();
                int upload_type = 0;//FileUploadUtils.TYPE_PROMOTER_MEAL;
                System.out.println("content:  "+ content);
                img_key = ""; //FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, promoter.getName(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
                qrCode = img_key;

				promoter.setQrCode(qrCode);
//                promoterService.updateById(promoter);

				new Thread(() -> {
					System.out.println(" <===== 线程开始 =====> " + System.currentTimeMillis());
					try{
						Thread.sleep(3000);//线程休眠5秒
						String bigImg = uploadPath + "/promoter/promoter_qr_bg.png";
						String bigOutImg = uploadPath + "/promoter/promoter_qr_bg.jpg";
//						String smallImg = uploadPath + "/" + FileUploadUtils.getUploadPrefix(upload_type) +  "promoter_qr_" + userNo + ".jpg";
//						String outPath = uploadPath + "/" + FileUploadUtils.getUploadPrefix(upload_type) +  "promoter_qr_" + userNo + ".jpg";

						//先将大图转成jpg
//						try {
//								ImageUtils.pngToJpg(bigImg, bigOutImg);
//							ImageUtils.bigImgAddSmallImgAndText(bigOutImg, smallImg, 118, 140, 200,200,null, 700, 700, outPath);
//						} catch (IOException e) {
//							e.printStackTrace();
//						}
					}catch (InterruptedException e){
						e.printStackTrace();
					}
					System.out.println(" <===== 线程结束 =====> " + System.currentTimeMillis());
				}).start();


				if (promoterService.updateById(promoter)) {
					return R.ok();
				}

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return R.okByRow(bl? 1 : 0);
    }



	/**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:promoter:edit')")
	public R<Void> resetQrCode(@RequestBody  Promoter promoter) {
		String img_key = "";
		if(promoter.getId()!=null){
			try{
				promoter = promoterService.getById(promoter.getId());
				if(promoter != null){
					String qrCode = "";
					String fileName = "promoter_qr_" + promoter.getUserNo() + ".jpg";
                    String content = "https://www.sdyuedou.com/wxmini/promoter/getInfo?pid=" + promoter.getId();
					int upload_type = 0;//FileUploadUtils.TYPE_PROMOTER_MEAL;
					System.out.println("content:  "+ content);
					img_key = ""; //FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, promoter.getName(), null, uploadPath +"/" + img_key, true, fileName, upload_type);
					qrCode = img_key;
					final String userNo =  promoter.getUserNo();

					promoter.setQrCode(qrCode);

					new Thread(() -> {
						System.out.println(" <===== 线程开始 =====> " + System.currentTimeMillis());
						try{
							Thread.sleep(3000);//线程休眠5秒
//							String bigImg = uploadPath + "/promoter/promoter_qr_bg.png";
//							String bigOutImg = uploadPath + "/promoter/promoter_qr_bg.jpg";
//							String smallImg = uploadPath + "/" + FileUploadUtils.getUploadPrefix(upload_type) +  "promoter_qr_" + userNo + ".jpg";
//							String outPath = uploadPath + "/" + FileUploadUtils.getUploadPrefix(upload_type) +  "promoter_qr_" + userNo + ".jpg";
//
//							//先将大图转成jpg
//							try {
////								ImageUtils.pngToJpg(bigImg, bigOutImg);
//								ImageUtils.bigImgAddSmallImgAndText(bigOutImg, smallImg, 118, 140, 200,200,null, 700, 700, outPath);
//							} catch (IOException e) {
//								e.printStackTrace();
//							}
						}catch (InterruptedException e){
							e.printStackTrace();
						}
						System.out.println(" <===== 线程结束 =====> " + System.currentTimeMillis());
					}).start();

				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (promoterService.updateById(promoter)) {
				return R.ok();
			}
		}
		return R.failed();
	}


	/**
     * 修改平台推广员
     */
    @ApiOperation("修改平台推广员")
    @PreAuthorize("@pms.hasPermission('module:promoter:edit')")
    @SysLog("平台推广员")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Promoter promoter) {
        return R.okByRow(promoterService.updateById(promoter) ? 1 : 0);
    }

    /**
     * 审核平台推广员
     */
    @ApiOperation("修改平台推广员")
    @PreAuthorize("@pms.hasPermission('module:promoter:edit')")
    @SysLog("平台推广员")

    @PutMapping("/check")
    public R<Void> check(@Valid @RequestBody Promoter promoter) {
        if(promoter.getCheckState()==1){
//            WxUser wxUser = wxUserService.findById(promoter.getWxUserId());
//            if(wxUser!=null){
//				promoter.setName(wxUser.getNickName());
//			}
            resetQrCode(promoter);
            return R.okByRow(promoterService.updateById(promoter) ? 1 : 0);
        }else {
            return R.okByRow(0);
        }
    }

    /**
     * 删除平台推广员
     */
    @ApiOperation("删除平台推广员")
    @PreAuthorize("@pms.hasPermission('module:promoter:remove')")
    @SysLog("平台推广员")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(promoterService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
